package com.bitoon.basketdudes.api.taiwan;

import com.bitoon.basketdudes.jpa.*;
import com.bitoon.basketdudes.ws.Tienda;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.persistence.*;
import javax.servlet.http.*;
import org.apache.log4j.*;

public class Api {

    EntityManagerFactory emfBasket = null;
    Logger log = Logger.getLogger(Api.class);
    Properties configuracion = new Properties();

    public static final int INFO_TEAMNAME = 1;
    public static final int INFO_TEAMDUDDIES = 2;

    public Api() {
        try {
            emfBasket = PersistenceManager.getInstance().getEntityManagerFactory("jpa_basket");
        } catch (Exception e) {
            log.error("[ERROR][constructor]: No se pudo conectar a la base de datos: ", e);
        }

        // Leer fichero de propiedades

        ClassLoader loader = Api.class.getClassLoader();
        if (loader==null) {
            loader = ClassLoader.getSystemClassLoader();
        }

        String propFile = "config.properties";
        java.net.URL url = loader.getResource(propFile);
        
        try {
            configuracion.load(url.openStream());

            url.openStream().close();
        } catch (Exception e) {
            log.error("Could not load configuration file: ",e);
        }

    }

    public boolean checkApiKey(HttpServletRequest request, HttpServletResponse response) {
        boolean retorno     = false;
        String configApiKey = null;
        String reqApiKey    = null;

        log.debug("checkApiKey - A");
        if ( request.getParameter("apikey") != null) {
            reqApiKey = request.getParameter("apikey");          
        } else {
            log.debug("checkApiKey - Vacio");            
            return false;            
        }

        try {
            // Partner Bitoon            
            if ( reqApiKey.startsWith("1") ) {
                log.debug("checkApiKey - 1 Bitoon");
                configApiKey = configuracion.getProperty("api1.key");
            } else if ( reqApiKey.startsWith("2") ) {
                log.debug("checkApiKey - 2 Arkarena");
                configApiKey = configuracion.getProperty("api2.key");
            } else if ( reqApiKey.startsWith("3") ) {
                log.debug("checkApiKey - 3 ???");
                configApiKey = configuracion.getProperty("api3.key");
            } else if ( reqApiKey.startsWith("4") ) {
                log.debug("checkApiKey - 4 ???");
                configApiKey = configuracion.getProperty("api4.key");
            } else {
                log.debug("checkApiKey - C "+request.getParameter("apikey"));
                configApiKey = configuracion.getProperty("api.key");
            }
            log.debug("Comparando [" + reqApiKey + "] con [" + configApiKey + "]");

            if (reqApiKey.equals(configApiKey)) {
                retorno = true;
            }
        } catch (Exception e) {
            log.error("Error en checkApi: ", e);
        }

        return retorno;
    }

    public void addUser(HttpServletRequest request, HttpServletResponse response) {

        PrintWriter out = null;
        int retCode = 0;
        String retText = "";

        int userId = -1;

        EntityManager em = null;

        try {

            log.debug("init adduser ...");

            em = emfBasket.createEntityManager(); // check 07.08.2012

            String nick = URLDecoder.decode(request.getParameter("nick"),"UTF-8");
            String password = request.getParameter("password");

            if (!isValidSHA1(password)) {
                retCode = -2;
                retText = "SHA1 string is not valid";
            } else {
                log.debug("valid sha1");
                Query q = em.createNamedQuery("Usuario.findByNick");
                q.setParameter("nick", nick);
                List<Usuario> existsUser = q.getResultList();
                log.debug("existsUser: " + existsUser);
                if (!existsUser.isEmpty()) {
                    // The user already exists

                    retCode = -1;
                    retText = "Nick already exist";

                } else {
                    log.debug("create new user ...");
                    Usuario usuario = new Usuario();
                    usuario.setNick(nick.toLowerCase());
                    usuario.setNickMostrar(nick);
                    usuario.setPassword(password);
                    usuario.setIdiomaId("ZH");
                    usuario.setAdmin(0);
                    usuario.setStatus(1);
                    usuario.setfAlta(new Date());
                    usuario.setfAdmision(new Date());
                    usuario.setReputacion(99);

                    em.getTransaction().begin();
                    em.persist(usuario);
                    userId = usuario.getId();
                    em.getTransaction().commit();

                    retCode = 0;
                    retText = "Successfull operation. User has been inserted correctly";
                }
            }
        } catch (Exception e) {
            log.error("Error: " , e);
            retCode = -3;
            retText = "General error";
            userId = -1;
        } finally {
            try { em.close(); } catch (Exception e) { } // revisado 09/08/2012
        }

        // Pintar la salida

        try {
            out = response.getWriter();
            out.print("code="+retCode+";code_text="+retText+";userid="+userId);
        } catch (Exception e) {
            log.error("Error trying to print the output: ", e);
        }
    }


    public void modifyPassword(HttpServletRequest request, HttpServletResponse response) {

        PrintWriter out = null;
        int retCode = 0;
        String retText = "";

        EntityManager em = null;

        try {

            em = emfBasket.createEntityManager(); // check 07.08.2012

            String nick = URLDecoder.decode(request.getParameter("nick"),"UTF-8");
            String password = request.getParameter("password");

            if (!isValidSHA1(password)) {
                retCode = -2;
                retText = "SHA1 string is not valid";
            } else {
                Query q = em.createNamedQuery("Usuario.findByNick");
                q.setParameter("nick", nick);
                List<Usuario> existsUser = q.getResultList();
                log.debug("existsUser: " + existsUser);
                if (existsUser.isEmpty()) {
                    // The user doesn't exist
                    retCode = -1;
                    retText = "Nick doesn't exist";
                } else {
                    em.getTransaction().begin();
                    Usuario usuario = em.find(Usuario.class, existsUser.get(0).getId());

                    usuario.setPassword(password);                    
                    em.persist(usuario);

                    em.getTransaction().commit();

                    retCode = 0;
                    retText = "Successfull operation. Password has been modified correctly";
                }
            }
        } catch (Exception e) {
            log.error("Error: " , e);
            retCode = -3;
            retText = "General error";
        } finally {
            try { em.close(); } catch (Exception e) { } // revisado 09/08/2012
        }

        // Pintar la salida

        try {
            out = response.getWriter();
            out.print("code="+retCode+";code_text="+retText);
        } catch (Exception e) {
            log.error("Error trying to print the output: ", e);
        }
    }



    public void getTeams(HttpServletRequest request, HttpServletResponse response) {

        PrintWriter out = null;
        int retCode = 0;
        String retText = "";
        String teamsId = "";

        EntityManager em = null;

        try {

            em = emfBasket.createEntityManager(); // check 07.08.2012

            String nick = URLDecoder.decode(request.getParameter("nick"),"UTF-8");

            Query q = em.createNamedQuery("Usuario.findByNick");
            q.setParameter("nick", nick);
            List<Usuario> userList = q.getResultList();
            if (userList.isEmpty()) {
                // The user doesn't exist
                retCode = -1;
                retText = "User doesn't exist";
            } else {
                Usuario user = userList.get(0);
                q = em.createNamedQuery("Equipo.findByIdUsuario");
                q.setParameter("idUsuario", user.getId());
                List<Equipo> teamList = q.getResultList();

                for (Equipo team : teamList) {
                    teamsId += team.getId() + ",";
                }

                if (teamsId.length()>0) {
                    teamsId = teamsId.substring(0,teamsId.length()-1);
                }

                retCode = 0;
                retText = "Successfull operation.";
            }
        } catch (Exception e) {
            log.error("Error: " , e);
            retCode = -3;
            retText = "General error";
        } finally {
            try { em.close(); } catch (Exception e) { } // revisado 09/08/2012
        }

        // Pintar la salida

        try {
            out = response.getWriter();
            out.print("code="+retCode+";code_text="+retText+";team_list="+teamsId);
        } catch (Exception e) {
            log.error("Error trying to print the output: ", e);
        }
    }


    // Este m�todo se usa tanto para getTeamData como para getDuddies

    public void getTeamInfo(HttpServletRequest request, HttpServletResponse response, int typeInfo) {

        PrintWriter out = null;
        int retCode = 0;
        String retText = "";

        String teamName = "";
        String teamNick = "";
        long duddies = 0;

        EntityManager em = null;

        try {

            em = emfBasket.createEntityManager(); // check 07.08.2012

            Integer teamid = Integer.parseInt(request.getParameter("teamid"));

            Equipo team = em.find(Equipo.class, teamid);
            if (team == null) {
                // The team doesn't exist
                retCode = -1;
                retText = "Team doesn't exist";
            } else {
                teamName = team.getNombre();
                teamNick = team.getNick();
                duddies = team.getPuntos();

                retCode = 0;
                retText = "Successfull operation.";
            }
        } catch (Exception e) {
            log.error("Error: " , e);
            retCode = -3;
            retText = "General error";
        } finally {
            try { em.close(); } catch (Exception e) { } // revisado 09/08/2012
        }

        // Pintar la salida

        try {
            out = response.getWriter();
            switch (typeInfo) {
                case INFO_TEAMNAME:
                    out.print("code="+retCode+";code_text="+retText+";team_name="+teamName+";team_nick="+teamNick);
                    break;
                case INFO_TEAMDUDDIES:
                    out.print("code="+retCode+";code_text="+retText+";current_duddies="+duddies);
                    break;
            }
        } catch (Exception e) {
            log.error("Error trying to print the output: ", e);
        }
    }


    public void getBitoons(HttpServletRequest request, HttpServletResponse response) {

        PrintWriter out = null;
        int retCode = 0;
        String retText = "";
        float bitoons = 0;

        EntityManager em = null;

        try {

            em = emfBasket.createEntityManager(); // check 07.08.2012

            String nick = URLDecoder.decode(request.getParameter("nick"),"UTF-8");

            Query q = em.createNamedQuery("Usuario.findByNick");
            q.setParameter("nick", nick);
            List<Usuario> existsUser = q.getResultList();
            log.debug("existsUser: " + existsUser);
            if (existsUser.isEmpty()) {
                // The user doesn't exist
                retCode = -1;
                retText = "Nick doesn't exist";
            } else {
                Usuario usuario = existsUser.get(0);

                bitoons = usuario.getCreditos();

                retCode = 0;
                retText = "Successfull operation.";
            }
        } catch (Exception e) {
            log.error("Error: " , e);
            retCode = -3;
            retText = "General error";
        } finally {
            try { em.close(); } catch (Exception e) { } // revisado 09/08/2012
        }

        // Pintar la salida

        try {
            out = response.getWriter();
            out.print("code="+retCode+";code_text="+retText+";bitoons="+bitoons);
        } catch (Exception e) {
            log.error("Error trying to print the output: ", e);
        }
    }

    /*
    Retornos:
     0 - ok
    -1 - user not exists
    -3 - error general
    -4 - incorrect api key
    -5 - incorrect remote_id
    -6 - remote_id not exists
    -7 - incorrect bitoons amount
    -8 - zero bitoons amount
    -9 - incorrect currency
   -10 - incorrect amount parameter
   -11 - incorrect commission parameter
   -12 - incorrect discount parameter
   -13 - incorrect payment_method parameter
   -14 - incorrect transaction_id length
   -15 - incorrect transaction_id2 length
   -16 - currency without amount or visa
    */

    public void addBitoons(HttpServletRequest request, HttpServletResponse response) {

        PrintWriter out             = null;
        int         retCode         =  0;
        String      retText         = "";
        String      reqApiKey       = "";
        String      nick            = null;
        int         userId          = -1;
        int         bitoons         =  0;
        int         descuento       =  0;
        short       pasarela_id     =  0;
        short       partner_id      =  1; // bitoon
        float       currentBitoons  =  0;
        
        String      currency="";
        String      clave   ="";
        String      clave2  ="";
        BigDecimal  importe =BigDecimal.ZERO;
        BigDecimal  comision=BigDecimal.ZERO;
        
        Query       q               = null;
        Usuario     usuario_actualizar = null;
        EntityManager em            = null;
        
        try {

            if ( request.getParameter("apikey") != null) {
                reqApiKey = request.getParameter("apikey");          
            }    
            
            em = emfBasket.createEntityManager(); // check 07.08.2012
            if ( request.getParameter("nick")!= null ) {
                nick = URLDecoder.decode(request.getParameter("nick"),"UTF-8");
                q = em.createNamedQuery("Usuario.findByNick");
                q.setParameter("nick", nick);
            }
            if ( request.getParameter("user_id")!= null ) {
                userId = Integer.parseInt(URLDecoder.decode(request.getParameter("user_id"),"UTF-8"));
                q = em.createNamedQuery("Usuario.findById");
                q.setParameter("id", userId);                                
            }
            if ( retCode == 0 && q!= null) {
                List<Usuario> listUsers = null;
                listUsers = q.getResultList();
                
                if ( listUsers != null && listUsers.size()!=0  ) {
                    usuario_actualizar = listUsers.get(0);
                    log.debug("Usuario a ingresar "+usuario_actualizar.getId() +" "+ 
                            usuario_actualizar.getNick() + " "+usuario_actualizar.getCreditos());
                } else {
                    retCode = -1;
                    if ( userId == -1) {
                        retText = "Nick doesn't exist";
                    } else {
                        retText = "UserId doesn't exist";                    
                    }                    
                }                    
            }

            
            // Nuevos Parametros para Arkarena
            // currency: (obligatorio) Turkish Lyras "TRY"
            // amount:   (obligatorio) Effective amount of real money
            // discount: (default 0) amount of bitoons, given as free 
            // payment_method: (default 0 free gmtools) numeric id of payment gateway used.
            //                 (internal field pasarela_id)
            // transaction_id: (optional) alphanumeric 80 character length
            // transaction_id2: (optional) alphanumeric 80 character length
            if ( request.getParameter("currency")== null ) {
                retCode = -9;                    
                retText = "Incorrect Currency";                   
            } else {
                currency = request.getParameter("currency").toUpperCase();
                
                q = em.createNamedQuery("Moneda.findById");
                q.setParameter("id", currency);
                List<Moneda> listMoneda = null;
                listMoneda = q.getResultList();
                
                if ( listMoneda == null || listMoneda.size()==0  ) {
                    retCode = -9;                    
                    retText = "Incorrect Currency";                                       
                }
                
            }
            if ( request.getParameter("amount")== null ) {
                retCode = -10;                    
                retText = "Incorrect Amount";                   
            } else {
                importe = BigDecimal.valueOf(Double.parseDouble(request.getParameter("amount")));                    
                if ( importe.floatValue() < 0 ) {
                    retCode = -10;                    
                    retText = "Incorrect Amount";                                           
                }
            }
            if ( request.getParameter("commission")!= null ) {
                comision = BigDecimal.valueOf(Double.parseDouble(request.getParameter("commission")));                    
                if ( comision.floatValue() < 0 ) {
                    retCode = -11;                    
                    retText = "Incorrect Commission";                                           
                }
            }
            if ( request.getParameter("discount")!= null ) {
                descuento = Integer.parseInt(request.getParameter("discount"));
                if ( descuento < 0 ) {
                    retCode = -12;                    
                    retText = "Incorrect Discount";                                           
                }
            }
            if ( request.getParameter("payment_method")!= null ) {
                pasarela_id = Short.parseShort(request.getParameter("payment_method"));
                if ( pasarela_id < 0 ) {
                    retCode = -13;                    
                    retText = "Incorrect payment_method";                   
                }
            }
            if ( request.getParameter("transaction_id")!= null ) {
                clave = request.getParameter("transaction_id");
                if ( clave.length()>80 ) {
                    retCode = -14;                    
                    retText = "Incorrect transaction_id length";
                }
            }
            if ( request.getParameter("transaction_id2")!= null ) {
                clave2 = request.getParameter("transaction_id2");
                if ( clave2.length()>80 ) {                
                    retCode = -15;                    
                    retText = "Incorrect transaction_id2 length";                   
                }
            }
            
            if ( request.getParameter("amount")!= null && request.getParameter("currency")== null) {
                retCode = -9;                    
                retText = "Incorrect Currency";                                       
            }
                    
            if ( request.getParameter("amount")== null && request.getParameter("currency")!= null) {
                retCode = -10;                    
                retText = "Incorrect Amount";                                                           
            } 
            
            
            if ( reqApiKey.startsWith( "2" )) {   
                // Parnert Arkarena
                userId = -1;
                partner_id=2;
                
                if ( request.getParameter("remote_id")== null ) {
                    retCode = -5;                    
                    retText = "Incorrect Remote_Id";                   
                } else {
                    int remote_id = Integer.parseInt(request.getParameter("remote_id"));
                    
                    // Buscamos el registro remoto 
                    Query qpu = em.createNamedQuery("PartnerUsuario.findByRemoteId");                        
                    qpu.setParameter("partner_id", (short)2);                                        
                    qpu.setParameter("remote_id", remote_id);                                        

                    List<PartnerUsuario> existsRemoteUser = qpu.getResultList();
                    if ( existsRemoteUser != null && existsRemoteUser.size()>0 ) {
                        usuario_actualizar = existsRemoteUser.get(0).getUsuario();
                        log.debug("Usuario turco a ingresar "+usuario_actualizar.getId() +" "+ 
                                usuario_actualizar.getNick() + " "+usuario_actualizar.getCreditos());
                    } else {
                        retCode = -6;                    
                        retText = "Remote_Id doesn'nt exist";                                           
                    }
                }                
            }

            
            if ( request.getParameter("bitoons") == null ) {
                retCode = -8;                    
                retText = "Zero bitoons amount";                                    
            } else {
                bitoons = Integer.parseInt(request.getParameter("bitoons"));
                if ( bitoons < 1 ) {
                    retCode = -7;                    
                    retText = "Incorrect bitoons amount";                    
                }
            }
            
            if ( retCode == 0) {
                    // Recharge Bitoons
                    Ingreso deposit = new Ingreso();
                    currentBitoons = usuario_actualizar.getCreditos();
                    deposit.setUsuarioId (usuario_actualizar.getId());
                    deposit.setBitoones  (bitoons);
                    deposit.setDescuento (descuento);
                    deposit.setFPeticion (new Date());
                    deposit.setFFin      (new Date());
                    deposit.setMoneda    (currency);
                    deposit.setClave     (clave);
                    deposit.setClave2    (clave2);
                    deposit.setPasarelaId(pasarela_id);
                    deposit.setPartnerId (partner_id);
                    deposit.setImporte   (importe);
                    deposit.setComision  (comision);
                    deposit.setJuegoId   ((short)1);
/*
                    Usuario usuario = em.find(Usuario.class, usuario_actualizar.getId());
                    usuario.setCreditos(usuario.getCreditos()+bitoons);
*/
                    usuario_actualizar.setCreditos(usuario_actualizar.getCreditos()+bitoons);                    
                    
                    // Chequeamos los permisos del partner sobre el usuario
                    if ( checkPartner( em, usuario_actualizar, request ) ) {
                        em.getTransaction().begin();
                        em.persist(deposit);
                        em.persist(usuario_actualizar);
                        em.getTransaction().commit();

                        retCode = 0;
                        currentBitoons+=bitoons;
                        retText = "Successfull operation";
                    } else {
                        retCode = -4;                    
                        retText = "Incorrect Apikey";
                    }
                // }
            }
        } catch (Exception e) {
            log.error("Error: " , e);
            retCode = -3;
            retText = "General error";
            userId = -1;
        } finally {
            try { em.close(); } catch (Exception e) { } // revisado 09/08/2012
        }

        // Pintar la salida

        try {
            out = response.getWriter();
            out.print("code="+retCode+";code_text="+retText+";current_bitoons="+currentBitoons);
        } catch (Exception e) {
            log.error("Error trying to print the output: ", e);
        }
    }


    private boolean isValidSHA1(String hash) {
        return hash.matches("[a-fA-F0-9]{40}");
    }


    public void addDuddies(HttpServletRequest request, HttpServletResponse response) {

        PrintWriter out = null;
        int retCode = 0;
        String retText = "";

        int nuevo_credito = -1;
        int equipo_id = -1;
        int cantidad = -1;
        EntityManager em = null;

        try {

            log.debug("init addDuddies ...");

            em = emfBasket.createEntityManager(); // check 07.08.2012

            if ( request.getParameter("duddies")== null ||
                 Integer.parseInt(request.getParameter("duddies")) == 0) {
                retCode = -3;
                retText = "Duddies shouldn't be 0";
            } else {
                cantidad = Integer.parseInt(request.getParameter("duddies"));
            }
            if ( request.getParameter("teamid") == null ||
                 Integer.parseInt(request.getParameter("teamid")) < 1) {
                    retCode = -4;
                    retText = "Team identifier not valid";
            } else {
                equipo_id = Integer.parseInt(request.getParameter("teamid"));
            }

            if ( retCode == 0 ) {
                em.getTransaction().begin();
                log.debug("valid cantidad equipo " + equipo_id );
                Query q = em.createNamedQuery("Equipo.findById");
                q.setParameter("idEquipo", equipo_id);
                List<Equipo> lista_equipo = q.getResultList();
                log.debug("exists Equipo: " + lista_equipo);
                if (lista_equipo.isEmpty() ) {
                    // The equipo don't exists
                    retCode = -1;
                    retText = "Team doesn't exists";

                } else {
                    if ( cantidad <0 && lista_equipo.get(0).getPuntos()<Math.abs(cantidad)  ) {
                        retCode = -5;
                        retText = "Duddies must be lower than current amount.";                     
                    } else {
                        log.debug("increasing duddies equipo_id" + equipo_id );
                        nuevo_credito = lista_equipo.get(0).getPuntos()+cantidad;
                        lista_equipo.get(0).setPuntos( nuevo_credito  );

                        retCode = 0;
                        retText = "Successfull operation. Duddies added.";
                    }
                }
                em.getTransaction().commit();
            }
        } catch (Exception e) {
            log.error("Error: " , e);
            retCode = -3;
            retText = "General error";
            nuevo_credito = -1;
        } finally {
            try { em.close(); } catch (Exception e) { } // revisado 09/08/2012
        }

        // Pintar la salida

        try {
            out = response.getWriter();
            out.print("code="+retCode+";code_text="+retText+";current_duddies="+nuevo_credito);
        } catch (Exception e) {
            log.error("Error trying to print the output: ", e);
        }
    }

    public void giveItem(HttpServletRequest request, HttpServletResponse response) {

        PrintWriter out         = null;
        int         retCode     = 0;
        String      retText     = "";
        String      retorno     = "";
        Boolean     sustituir   = false;

        int equipo_id       = -1;
        int jugador_id      = -1;
        int objeto_tipo     = -1;
        int objeto_id       = -1;
        int unidades        = -1;
        int slot            = -1;

        EntityManager em = null;

        try {

            log.debug("init addDuddies ...");

            em = emfBasket.createEntityManager(); // check 07.08.2012

            if ( request.getParameter("itemtype")== null ||
                 Integer.parseInt(request.getParameter("itemtype")) < 1) {
                retCode = -5;
                retText = "objeto_tipo incorrect";
            } else {
                objeto_tipo = Integer.parseInt(request.getParameter("itemtype"));
            }

            if ( request.getParameter("teamid") == null ||
                 Integer.parseInt(request.getParameter("teamid")) < 1) {
                    retCode = -5;
                    retText = "Team id incorrect";
            } else {
                equipo_id = Integer.parseInt(request.getParameter("teamid"));
            }

            if ( request.getParameter("itemid")== null ||
                 Integer.parseInt(request.getParameter("itemtype")) < 1) {
                retCode = -5;
                retText = "objeto_id incorrect";
            } else {
                objeto_id = Integer.parseInt(request.getParameter("itemid"));
            }

            if ( request.getParameter("units")== null ||
                 Integer.parseInt(request.getParameter("units")) < 1) {
                retCode = -5;
                retText = "incorrect units";
            } else {
                unidades = Integer.parseInt(request.getParameter("units"));
            }
            
            if ( request.getParameter("player_id")== null ||
                 Integer.parseInt(request.getParameter("player_id")) < 1) {
                jugador_id = 0;
            } else {
                jugador_id = Integer.parseInt(request.getParameter("player_id"));
            }

            if ( request.getParameter("slot")== null ||
                 Integer.parseInt(request.getParameter("slot")) < 1) {
                slot = 0;
            } else {
                slot = Integer.parseInt(request.getParameter("slot"));
            }
            
            
            if ( retCode == 0 ) {
                em.getTransaction().begin();
                log.debug("valid parameters " + equipo_id + " " + objeto_tipo + " " + objeto_id + " ");
                Query q = em.createNamedQuery("Equipo.findById");
                q.setParameter("idEquipo", equipo_id);
                List<Equipo> lista_equipo = q.getResultList();
                log.debug("exists Equipo: " + lista_equipo);
                if (lista_equipo.isEmpty() ) {
                    // The equipo don't exists
                    retCode = -12;
                    retText = "Equipo doesn't exists";

                } else {
                    Tienda tienda = new Tienda();
                    String ret_xml = tienda.comprar_moneda( "", equipo_id, (short)objeto_tipo, objeto_id,
                                                           (short)unidades, -1, true, 1, -1, jugador_id, slot );

                    // El retorno de la función tiene la forma:
                    //    error=0;credito=nnnn;puntos=pppp;
                    // Si es la compra de un sobre es:
                    //    error=0;credito=nnnn;puntos=pppp;carta1=id;carta2=id;carta3=id
                    // Si se produce un error
                    // Comprar un sobre que no existe
                    //    error=-3;descripcion=Error al comprar;
                    // Comprar un tipo de item no definido
                    //    error=-5;descripcion=Error al comprar;
                    // Comprar una carta no comprable
                    //    error=-4;descripcion=Error al comprar;
                    // Compra de una carta correcta
                    //    error=0;credito=9999.0;puntos=6175;
                    retorno = ret_xml;
                    if ( retorno.contains("error") == false )
                        retorno += "error=-1";
                    retorno = retorno.replaceFirst("error", "code");

                    if ( retorno.contains("descripcion") == false )
                        retorno += "descripcion=undefined";
                    retorno = retorno.replaceFirst("descripcion", "code_text");


                    sustituir   = true;
                    retCode     = 0;
                    retText     = "Item purchased";

                }
                em.getTransaction().commit();
            }
        } catch (Exception e) {
            log.error("Error: " , e);
            retCode = -3;
            retText = "General error";
        } finally {
            try { em.close(); } catch (Exception e) { } // revisado 09/08/2012
        }

        // Pintar la salida

        try {
            out = response.getWriter();
            if ( sustituir )
                out.print(retorno);
            else
                out.print("code="+retCode+";code_text="+retText+";"+retorno);
        } catch (Exception e) {
            log.error("Error trying to print the output: ", e);
        }
    }

    public void deleteUser(HttpServletRequest request, HttpServletResponse response) {

        PrintWriter out = null;
        int retCode = 0;
        String retText = "";
        float bitoons = 0;

        EntityManager em = null;

        try {
            log.debug("start deleteUser" );
            em = emfBasket.createEntityManager(); // check 07.08.2012
            String nick      ="";
            String p_password="";

            if ( request.getParameter("nick") == null ) {
                    retCode = -1;
                    retText = "nick parameter incorrect";
            } else {
                nick = URLDecoder.decode(request.getParameter("nick"),"UTF-8");
            }

            if ( request.getParameter("password") == null ) {
                    retCode = -1;
                    retText = "password parameter incorrect";
            } else {
                p_password = request.getParameter("password");
            }

            Query q = em.createNamedQuery("Usuario.findByNick");
            q.setParameter("nick", nick);
            List<Usuario> existsUser = q.getResultList();
            if (existsUser.isEmpty()) {
                log.debug("notExistsUser: " + nick );
                // The user doesn't exist
                retCode = -1;
                retText = "Nick doesn't exist";
            } else {
                log.debug("existsUser: " + existsUser.get(0).getNick());
                Usuario usuario = existsUser.get(0);

                if ( usuario.getPassword().compareToIgnoreCase(p_password) != 0  ) {
                    retCode = -2;
                    retText = "Password don't match";
                } else {
                    if ( usuario.getStatus() != 7 ) {
                        em.getTransaction().begin();

                        // El estado 7 es la baja voluntaria
                        usuario.setStatus(7);
                        usuario.setRobinson(2);
                        usuario.setPassword("");

                        em.persist(usuario);
                        em.getTransaction().commit();

                        retCode = 0;
                        retText = "Successfull operation.";
                    }
                }
            }
        } catch (Exception e) {
            log.error("Error: " , e);
            retCode = -3;
            retText = "General error";
        } finally {
            try { em.close(); } catch (Exception e) { } // revisado 09/08/2012
        }

        // Pintar la salida
        try {
            out = response.getWriter();
            out.print("code="+retCode+";code_text="+retText);
        } catch (Exception e) {
            log.error("Error trying to print the output: ", e);
        }
    }

    public boolean checkPartner( EntityManager em, Usuario p_usuario, HttpServletRequest request) {
        boolean retorno     = false;
        String reqApiKey    = null;

        log.debug("checkPartner - A");
        if ( request.getParameter("apikey") != null) {
            reqApiKey = request.getParameter("apikey");          
        } else {
            log.debug("checkPartner - Vacio");            
            return false;            
        }

        try {
            // Buscamos la region que tiene el usuario asignada
            Region region = p_usuario.getRegion();
            
            log.debug(" checkPartner Buscar Region: " + p_usuario.getRegion().getId() );
            
            Query q = em.createNamedQuery("Region.findById");
            q.setParameter("id", region.getId());
            List<Region> lista_region = q.getResultList();
            
            if ( lista_region == null ) {
                log.debug("NO EXISTE REGION" + region.getId());
                return false;
            }
            
            log.debug("checkPartner REGION ENCONTRADA " + lista_region.get(0).getPartner().getId().toString() + " apikey " + reqApiKey );
            
            // Region Turca
            if ( reqApiKey.startsWith( lista_region.get(0).getPartner().getId().toString() ) ) {
                retorno = true;
            } else {
                retorno = false;
            }
        } catch (Exception e) {
            log.error("Error en checkPartner: ", e);
        }

        return retorno;
    }
    
    
}